package com.berwin.services;

import android.app.Service;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.berwin.listener.ClipboardChangeListener;

public class ClipboardService extends Service {

    public static String lastClipboardContent = "";

    public class CustomBinder extends Binder {

        public void setListener(ClipboardChangeListener listener) {
            ClipboardService.this.listener = listener;
        }

        public ClipboardService getService() {
            return ClipboardService.this;
        }
    }

    private ClipboardChangeListener listener;
    private CustomBinder binder = new CustomBinder();
    private ClipboardManager mClipboardManager;
    private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener;

    @Override
    public void onCreate() {
        super.onCreate();
        this.registerClipEvents();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mClipboardManager != null && mOnPrimaryClipChangedListener != null) {
            mClipboardManager.removePrimaryClipChangedListener(mOnPrimaryClipChangedListener);
        }
    }

    /**
     * 注册剪切板复制、剪切事件监听
     */
    private void registerClipEvents() {
        mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        mOnPrimaryClipChangedListener = new ClipboardManager.OnPrimaryClipChangedListener() {
            @Override
            public void onPrimaryClipChanged() {
                if (mClipboardManager.hasPrimaryClip()
                        && mClipboardManager.getPrimaryClip().getItemCount() > 0) {
                    // 获取复制、剪切的文本内容
                    CharSequence content =
                            mClipboardManager.getPrimaryClip().getItemAt(0).getText();
                    if (!ClipboardService.lastClipboardContent.equals(content.toString())) {
                        Log.i("TAG", "复制、剪切的内容为：" + content);
                        ClipboardService.lastClipboardContent = content.toString();
                        if (ClipboardService.this.listener != null) {
                            ClipboardService.this.listener.onClipboardChanged(content.toString());
                        }
                    }
                }
            }
        };
        mClipboardManager.addPrimaryClipChangedListener(mOnPrimaryClipChangedListener);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }


}
